package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.bean.RegionStoreDataBean;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.PreferenceUtils;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.linjian.togetherbirthday.utils.ThreadPoolManager;
import com.linjian.togetherbirthday.utils.UiUtils;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PullBaseFragment extends Fragment implements View.OnClickListener {
    String className = this.getClass().getName();
    //listView2 的数据集合
    List<List<String>> mCataloguesAll;
    //listView1 的数据集合
    String mCatalogues1[];
    //listView2
    List<String> mCatalogues2;
    // 下拉容器
    private FrameLayout mDownMenu;
    // listView1
    private ListView item1;
    // listView2
    private ListView mItem2;
    private View mView;
    private int mFoodpoition;
    private Item1Adatper mItem1Adatper;
    private Item2Adatper mItem2Adatper;
    private long mItem1SelectedPosition = 0;
    private long mItem2SelectedPosition = 0;

//    String catalogues[][] = new String[][]{
//            new String[]{"全部美食", "本帮江浙菜", "川菜", "粤菜", "湘菜", "东北菜", "台湾菜", "新疆/清真", "素菜", "火锅", "自助餐", "小吃快餐", "日本", "韩国料理",
//                    "东南亚菜", "西餐", "面包甜点", "其他"},
//            new String[]{"全部休闲娱乐", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
//                    "DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
//            new String[]{"全部购物", "综合商场", "服饰鞋包", "运动户外", "珠宝饰品", "化妆品", "数码家电", "亲子购物", "家居建材"
//                    , "书店", "书店", "眼镜店", "特色集市", "更多购物场所", "食品茶酒", "超市/便利店", "药店"},
//            new String[]{"全部休闲娱乐", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
//                    "DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
//            new String[]{"全", "咖啡厅", "酒吧", "茶馆", "KTV", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
//                    "DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
//            new String[]{"全部", "咖啡厅", "酒吧", "茶馆", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
//                    "DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
//            new String[]{"全部休", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
//                    "DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
//            new String[]{"全部休闲", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
//                    "DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
//            new String[]{"全部休闲娱", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
//                    "DIY手工坊", "桌球馆", "桌面游戏"},
//            new String[]{"全部休闲娱乐", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
//                    "DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
//            new String[]{"全部休闲aaa", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
//                    "DIY手工坊", "桌球馆", "桌面游戏"},
//    };
//    String catalogues1[] = new String[]{"全部频道", "美食", "休闲娱乐", "购物", "酒店", "丽人", "运动健身", "结婚", "亲子", "爱车", "生活服务"};


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initView();
        return mDownMenu;
    }

    @Override
    public void onResume() {
        LoadDataAndSetListener();
        super.onResume();
    }

    private void initView() {
        mDownMenu = (FrameLayout) View.inflate(getActivity(), R.layout.down_menu, null);
        item1 = (ListView) mDownMenu.findViewById(R.id.item1);
        mItem2 = (ListView) mDownMenu.findViewById(R.id.item2);
        mView = mDownMenu.findViewById(R.id.bottom_view);
    }

    private void initListener() {
        mView.setOnClickListener(this);
        item1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Log.d("getChildCount", item1.getChildCount() + "");
//                Log.d("position", position + "");
                /**  用来保持 设置的itme信息**/
                /**---------------做个缓冲--------------------**/
                mItem1SelectedPosition = position;

                for (int i = 0; i < item1.getChildCount(); i++) {
                    //所有listview1 的item 字体颜色设置R.color.itemTextColor
                    ((TextView) (item1.getChildAt(i).findViewById(R.id.textview1))).setTextColor(getResources().getColor(R.color.itemTextColor));
                    //设置 listview1 的 item 未选中背景色 R.color.item1Color
                    item1.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.item1Color));
                }
                //选中条目设置 背景色和字体
                View view1 = mItem1Adatper.getView(position, view, parent);
                view1.setBackgroundColor(getResources().getColor(R.color.item2Color));
                //改变listview的数据
//                mCatalogues2 = mCataloguesAll[(int) mItem1SelectedPosition];
                mCatalogues2 = mCataloguesAll.get((int) mItem1SelectedPosition);
                mItem2Adatper.notifyDataSetChanged();
            }
        });
        mItem2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                /**  用来保持 设置的itme信息**/
                mItem2SelectedPosition = position;
                PreferenceUtils.setLong(getActivity(), className + "mItem1SelectedPosition", mItem1SelectedPosition);
                PreferenceUtils.setLong(getActivity(), className + "mItem2SelectedPosition", mItem2SelectedPosition);
                for (int i = 0; i < mItem2.getChildCount(); i++) {
                    ((TextView) (mItem2.getChildAt(i).findViewById(R.id.textview))).setTextColor(getResources().getColor(R.color.itemTextColor));
                    mItem2.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.item1Color));
                }
                mItem2Adatper.notifyDataSetChanged();
                //通过监听器
                checkListView2Close(mCatalogues1[(int) mItem1SelectedPosition], mCatalogues2.get((int)mItem2SelectedPosition));
                //获得宿主activity 调用activity的方法
//                ((MainOneActivity)getActivity()).setText(mCatalogues1[(int) mItem1SelectedPosition],mCatalogues2[(int) mItem2SelectedPosition]);

            }
        });
    }
    private class LoadDataTask implements Runnable{
        @Override
        public void run() {
            /**-------------网络请求数据--------------------**/
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            mCataloguesAll = catalogues;
//            mCatalogues1 = catalogues1;
            /**---------------模拟请求成功--------------------**/
            UiUtils.getMainHandler().post(new Runnable() {
                @Override
                public void run() {
                    Log.d("currentThread", Thread.currentThread() + "");
                    //模拟数据加载
                    initData();
                    initListener();
                }
            });
            /**-----------------------------------------------**/
        }
    }

    private void initData(){
        mItem1SelectedPosition = PreferenceUtils.getLong(getActivity(), className + "mItem1SelectedPosition", 0);
        mItem2SelectedPosition = PreferenceUtils.getLong(getActivity(), className + "mItem2SelectedPosition", 0);
//        mCatalogues2 = mCataloguesAll[(int) mItem1SelectedPosition];
        mCatalogues2 = mCataloguesAll.get((int)mItem1SelectedPosition);
        mFoodpoition = 0;
        if (mItem1Adatper == null) {
            mItem1Adatper = new Item1Adatper();
        }
        if (mItem2Adatper == null) {
            mItem2Adatper = new Item2Adatper();
        }
        item1.setAdapter(mItem1Adatper);
        mItem2.setAdapter(mItem2Adatper);
    };

    private void LoadDataAndSetListener() {

//        if (getArguments()!=null){
            regionStoreData("深圳",getActivity());
//        }

    }
    /**--------------------------关闭监听      --------------------------------------**/
    public interface OnCloseListener{
        void close();
    }
    private OnCloseListener mOnCloseListener;
    public void setOnTouchOutSide2CloseListener(OnCloseListener onCloseListener){
        if (mOnCloseListener == null){
            mOnCloseListener = onCloseListener;
        }
    }
    //通知DownMenu处理关闭事件
    @Override
    public void onClick(View v) {
//        ((MainOneActivity)(getActivity())).closeDownMenu();


//        Log.d("mOnCloseListener != null", (mOnCloseListener != null) + "");
//        if (mOnCloseListener != null){
//            mOnCloseListener.close();
//        }
    }
    /**--------------------------------------------------------------------------------**/
    /**
     *请求地区商圈数据
     */
    public void regionStoreData(String cityName,Context context){
        HttpUtils.doGet(HttpContant.URL + HttpContant.CityBycoordinate+"?cityName="+cityName
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(context, "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("regionStoreData",response.body().string()));
                    }
                });
    }

    RegionStoreDataBean regionStoreDataBean;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event){
        switch (event.getCls()){
            case "requestFail":
                TastyToast.makeText(getActivity(),"请求失败",TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                break;
            case "regionStoreData":
                Log.i("regionStoreData",event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        regionStoreDataBean = new Gson().fromJson(event.getData().toString(),RegionStoreDataBean.class);
                        mCatalogues1 = new String[regionStoreDataBean.getData().size()];
                        List<List<String>> lists = new ArrayList<>();
                        List<String> stringList;

                        for (int i = 0; i <regionStoreDataBean.getData().size(); i++) {
                            mCatalogues1[i] = regionStoreDataBean.getData().get(i).getDistrict_name();
                            stringList = new ArrayList<>();
                            for (int j = 0; j < regionStoreDataBean.getData().get(i).getNeighborhoods().size(); j++) {
                                stringList.add(regionStoreDataBean.getData().get(i).getNeighborhoods().get(j));
                            }
                            lists.add(stringList);
                        }
                        mCataloguesAll = lists;
                        //加载数据 开异步线程
                        ThreadPoolManager.getLongPool().execute(new LoadDataTask());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    /**--------------------------回显监听      --------------------------------------**/
    public interface OnSetDataListener{
        void setData(String data1,String data2);
    }
    private OnSetDataListener mOnSetDataListener;
    public void setOnSetDataListener(OnSetDataListener onSetDataListener){
        if (mOnSetDataListener == null){
            mOnSetDataListener = onSetDataListener;
        }
    }
    protected void checkListView2Close(String superPosition,String subPosition){
        if (mOnSetDataListener != null){
            mOnSetDataListener.setData(superPosition,subPosition);
            Log.i("checkListView2Close",superPosition+subPosition);
        }
    }
    /**--------------------------------------------------------------------------------**/
    private class Item1Adatper extends BaseAdapter {
        @Override
        public int getCount() {
            return mCatalogues1.length;
        }

        @Override
        public Object getItem(int position) {
            return mCatalogues1[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            // TODO Auto-generated method stub
            Item1ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.sublist_item, null);
                viewHolder = new Item1ViewHolder();
                viewHolder.textView = (TextView) convertView
                        .findViewById(R.id.textview1);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (Item1ViewHolder) convertView.getTag();
            }
            viewHolder.textView.setText(mCatalogues1[position]);
            viewHolder.textView.setTextColor(getResources().getColor(R.color.itemTextColor));
            //因为数据没变化
            convertView.setBackgroundColor(getResources().getColor(R.color.item1Color));
            //

            if (position == mItem1SelectedPosition){
                viewHolder.textView.setTextColor(getResources().getColor(R.color.buttonSelectColor));
                convertView.setBackgroundColor(getResources().getColor(R.color.item2Color));
            }

            return convertView;
        }
    }

    private class Item2Adatper extends BaseAdapter {


        @Override
        public int getCount() {
            return mCatalogues2.size();
        }

        @Override
        public Object getItem(int position) {
            return mCatalogues2.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            Item2ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.mylist_item, null);
                holder = new Item2ViewHolder();
                holder.textView = (TextView) convertView.findViewById(R.id.textview);
                convertView.setTag(holder);
            } else {
                holder = (Item2ViewHolder) convertView.getTag();
            }
            holder.textView.setText(mCatalogues2.get(position));
            holder.textView.setTextColor(getResources().getColor(R.color.itemTextColor));

            mItem2SelectedPosition = PreferenceUtils.getLong(getActivity(),className+"mItem2SelectedPosition",0);
            long currentItem1Postion = PreferenceUtils.getLong(getActivity(),className+"mItem1SelectedPosition",0);

            if (mItem1SelectedPosition == currentItem1Postion && position == mItem2SelectedPosition){
                holder.textView.setTextColor(getResources().getColor(R.color.buttonSelectColor));
            }
            convertView.setBackgroundColor(getResources().getColor(R.color.item2Color));
            return convertView;
        }
    }
    public static class Item1ViewHolder {
        public TextView textView;
        public ImageView imageView;
        public LinearLayout layout;
    }

    public static class Item2ViewHolder {
        public TextView textView;
    }
}
